
import { config } from "./config";
import { db } from "./db";
import { authApi } from "../api/auth/index";
import { LoginReq, LoginRes, RolesPerms, TokenRes } from "../api/auth/types";
import { ResponseData } from "../api/types";

//认证
class Auth {

  /** 检查登录是否有效？. */
  checkLogin(): boolean {
    if (db.getToken() && !db.isTokenExpire()) {
      return true;
    }
    return false;
  }

  // 检查角色
  checkRole(role: string): boolean {
    // 获取roleCodes
    const roleCodes: Array<string> = db.getRoleCodes();
    return roleCodes.length > 0 && roleCodes.indexOf(role) !== -1;
  }

  /** 静默登录 */
  silentLogin(): Promise<LoginRes> {
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          console.log(res)
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if (res.code) {
            authApi.miniappLogin({
              loginCode: res.code,
              appId: config.appId
            } as LoginReq).then((response: ResponseData<LoginRes>) => {
              console.log(response.data);
              if (response.code === 200 && response.data.status === true) {
                db.loginStorage(response.data);
                console.log("login success");
                this.getRolePerm().then(() => {
                  resolve(response.data);
                });
              } else if (response.code === 200) {
                console.log("to login page");
                db.unregisteredStorage(response.data);
                resolve(response.data);
              } else {
                reject(response.message);
              }
            })
          }
        },
        fail: fail => {
          console.log('登录失败', fail.errMsg)
          reject(fail.errMsg)
        }
      })
    });
  }

  phoneCodeLogin(phoneCode: string): Promise<LoginRes> {
    return new Promise<LoginRes>((resolve, reject) => {
      authApi.miniappPhoneNumber({
        phoneCode: phoneCode,
        cacheKey: wx.getStorageSync("cacheKey"),
        appId: config.appId
      }).then((resp: ResponseData<LoginRes>) => {
        if (resp.code === 200 && resp.data.status === true) {
          db.loginStorage(resp.data);
          console.log("login success");
          this.getRolePerm().then(() => {
            resolve(resp.data);
          });
        } else {
          reject(resp.message);
        }
      }
      );
    });
  }


  // 获取角色
  getRolePerm(): Promise<RolesPerms> {
    return new Promise<RolesPerms>((resolve, reject) => {
      authApi.userRolesPerms().then((response: ResponseData<RolesPerms>) => {
        db.rolesPermsStorage(response.data);
        resolve(response.data);
      }).catch(() => {
        reject("获取角色权限错误！");
      });
    });
  }

  // 刷新Token.
  refreshToken(): Promise<boolean> {
    return new Promise<boolean>((resolve, reject) => {
      authApi.refreshToken({
        tenant: config.tenant,
        refreshToken: db.getRefreshToken(),
        clientId: config.appId
      }).then((response: ResponseData<TokenRes>) => {
        db.tokenStorage(response.data);
        resolve(true);
      }).catch((error) => {
        reject(error);
      })
    })
  }
}

const auth = new Auth();

export { auth }

